home *** CD-ROM | disk | FTP | other *** search
/ Clickx 115 / Clickx 115.iso / software / tools / windows / tails-i386-0.16.iso / live / filesystem.squashfs / usr / lib / perl5 / autobox.pod < prev    next >
Encoding:
Text File  |  2010-03-19  |  17.3 KB  |  679 lines

  1. =pod
  2.  
  3. =head1 NAME
  4.  
  5. autobox - call methods on native types
  6.  
  7. =head1 SYNOPSIS
  8.  
  9.     use autobox;
  10.  
  11.     # integers
  12.  
  13.         my $range = 10->to(1); # [ 10, 9, 8, 7, 6, 5, 4, 3, 2, 1 ]
  14.  
  15.     # floats
  16.  
  17.         my $error = 3.1415927->minus(22/7)->abs();
  18.  
  19.     # strings
  20.  
  21.         my @list = 'SELECT * FROM foo'->list();
  22.         my $greeting = "Hello, world!"->upper(); # "HELLO, WORLD!"
  23.  
  24.         $greeting->for_each(\&character_handler);
  25.  
  26.     # arrays and array refs
  27.  
  28.         my $schwartzian = @_->map(...)->sort(...)->map(...);
  29.         my $hash = [ 'SELECT * FROM foo WHERE id IN (?, ?)', 1, 2 ]->hash();
  30.  
  31.     # hashes and hash refs
  32.  
  33.         { alpha => 'beta', gamma => 'vlissides' }->for_each(...);
  34.         %hash->keys();
  35.  
  36.     # code refs
  37.  
  38.         my $plus_five = (\&add)->curry()->(5);
  39.         my $minus_three = sub { $_[0] - $_[1] }->reverse->curry->(3);
  40.  
  41.     # can, isa, VERSION, import and unimport can be accessed via autobox_class
  42.  
  43.         42->autobox_class->isa('MyNumber')
  44.         say []->autobox_class->VERSION
  45.  
  46. =head1 DESCRIPTION
  47.  
  48. The autobox pragma allows methods to be called on integers, floats, strings, arrays,
  49. hashes, and code references in exactly the same manner as blessed references.
  50.  
  51. The autoboxing is transparent: boxed values are not blessed into their (user-defined)
  52. implementation class (unless the method elects to bestow such a blessing) - they simply
  53. use its methods as though they are.
  54.  
  55. The classes (packages) into which the native types are boxed are fully configurable.
  56. By default, a method invoked on a non-object is assumed to be
  57. defined in a class whose name corresponds to the C<ref()> type of that
  58. value - or SCALAR if the value is a non-reference.
  59.  
  60. This mapping can be overridden by passing key/value pairs to the C<use autobox>
  61. statement, in which the keys represent native types, and the values
  62. their associated classes.
  63.  
  64. As with regular objects, autoboxed values are passed as the first argument of the specified method.
  65. Consequently, given a vanilla C<use autobox>:
  66.  
  67.     "Hello, world!"->upper()
  68.  
  69. is invoked as:
  70.  
  71.     SCALAR::upper("hello, world!")
  72.  
  73. while:
  74.  
  75.     [ 1 .. 10 ]->for_each(sub { ... })
  76.  
  77. resolves to:
  78.  
  79.     ARRAY::for_each([ 1 .. 10 ], sub { ... })
  80.  
  81. Values beginning with the array C<@> and hash C<%> sigils are passed by reference, i.e. under the default bindings:
  82.  
  83.     @array->join(', ')
  84.     @{ ... }->length()
  85.     %hash->keys()
  86.     %$hash->values()
  87.  
  88. are equivalent to:
  89.  
  90.     ARRAY::join(\@array, ', ')
  91.     ARRAY::length(\@{ ... })
  92.     HASH::keys(\%hash)
  93.     HASH::values(\%$hash)
  94.  
  95. Multiple C<use autobox> statements can appear in the same scope. These are merged both "horizontally" (i.e.
  96. multiple classes can be associated with a particular type) and "vertically" (i.e. multiple classes can be associated
  97. with multiple types).
  98.  
  99. Thus:
  100.  
  101.     use autobox SCALAR => 'Foo';
  102.     use autobox SCALAR => 'Bar';
  103.  
  104. - associates SCALAR types with a synthetic class whose C<@ISA> includes both C<Foo> and C<Bar> (in that order).
  105.  
  106. Likewise:
  107.  
  108.     use autobox SCALAR => 'Foo';
  109.     use autobox SCALAR => 'Bar';
  110.     use autobox ARRAY  => 'Baz';
  111.  
  112. and
  113.  
  114.     use autobox SCALAR => [ 'Foo', 'Bar' ];
  115.     use autobox ARRAY  => 'Baz';
  116.  
  117. - bind SCALAR types to the C<Foo> and C<Bar> classes and ARRAY types to C<Baz>.  
  118.  
  119. C<autobox> is lexically scoped, and bindings for an outer scope
  120. can be extended or countermanded in a nested scope:
  121.  
  122.     {
  123.         use autobox; # default bindings: autobox all native types
  124.         ...
  125.  
  126.         {
  127.             # appends 'MyScalar' to the @ISA associated with SCALAR types
  128.             use autobox SCALAR => 'MyScalar';
  129.             ...
  130.         }
  131.  
  132.         # back to the default (no MyScalar)
  133.         ...
  134.     }
  135.  
  136. Autoboxing can be turned off entirely by using the C<no> syntax:
  137.  
  138.     {
  139.         use autobox;
  140.         ...
  141.         no autobox;
  142.         ...
  143.     }
  144.  
  145. - or can be selectively disabled by passing arguments to the C<no autobox> statement:
  146.  
  147.     use autobox; # default bindings
  148.  
  149.     no autobox qw(SCALAR);
  150.  
  151.     []->foo(); # OK: ARRAY::foo([])
  152.  
  153.     "Hello, world!"->bar(); # runtime error
  154.  
  155. Autoboxing is not performed for barewords i.e. 
  156.  
  157.     my $foo = Foo->new();
  158.  
  159. and:
  160.  
  161.     my $foo = new Foo;
  162.  
  163. behave as expected.
  164.  
  165. Methods are called on native types by means of the L<arrow operator|perlop/"The Arrow Operator">. As with
  166. regular objects, the right hand side of the operator can either be a bare method name or a variable containing
  167. a method name or subroutine reference. Thus the following are all valid:
  168.  
  169.     sub method1 { ... }
  170.     my $method2 = 'some_method';
  171.     my $method3 = sub { ... };
  172.     my $method4 = \&some_method;
  173.  
  174.     " ... "->method1();
  175.     [ ... ]->$method2();
  176.     { ... }->$method3();
  177.     sub { ... }->$method4();
  178.  
  179. A native type is only asociated with a class if the type => class mapping
  180. is supplied in the C<use autobox> statement. Thus the following will not work:
  181.  
  182.     use autobox SCALAR => 'MyScalar';
  183.  
  184.     @array->some_array_method();
  185.  
  186. - as no class is specified for the ARRAY type. Note: the result of calling a method 
  187. on a native type that is not associated with a class is the usual runtime error message:
  188.  
  189.     Can't call method "some_array_method" on unblessed reference at ...
  190.  
  191. As a convenience, there is one exception to this rule. If C<use autobox> is invoked with no arguments
  192. (ignoring the DEBUG option) the four main native types are associated with classes of the same name.
  193.  
  194. Thus:
  195.  
  196.     use autobox;
  197.  
  198. - is equivalent to:
  199.  
  200.     use autobox
  201.         SCALAR => 'SCALAR',
  202.         ARRAY  => 'ARRAY',
  203.         HASH   => 'HASH',
  204.         CODE   => 'CODE';
  205.  
  206. This facilitates one-liners and prototypes:
  207.  
  208.     use autobox;
  209.  
  210.     sub SCALAR::split { [ split '', $_[0] ] }
  211.     sub ARRAY::length { scalar @{$_[0]} }
  212.  
  213.     print "Hello, world!"->split->length();
  214.  
  215. However, using these default bindings is not recommended as there's no guarantee that another 
  216. piece of code won't trample over the same namespace/methods.
  217.  
  218. =head1 OPTIONS
  219.  
  220. A mapping from native types to their user-defined classes can be specified
  221. by passing a list of key/value pairs to the C<use autobox> statement.
  222.  
  223. The following example shows the range of valid arguments:
  224.  
  225.     use autobox
  226.         SCALAR    => 'MyScalar'                     # class name
  227.         ARRAY     => 'MyNamespace::',               # class prefix (ending in '::')
  228.         HASH      => [ 'MyHash', 'MyNamespace::' ], # one or more class names and/or prefixes
  229.         CODE      => ...,                           # any of the 3 value types above
  230.         INTEGER   => ...,                           # any of the 3 value types above
  231.         FLOAT     => ...,                           # any of the 3 value types above
  232.         NUMBER    => ...,                           # any of the 3 value types above
  233.         STRING    => ...,                           # any of the 3 value types above
  234.         UNDEF     => ...,                           # any of the 3 value types above
  235.         UNIVERSAL => ...,                           # any of the 3 value types above
  236.         DEFAULT   => ...,                           # any of the 3 value types above
  237.         DEBUG     => ...;                           # boolean or coderef
  238.  
  239. The INTEGER, FLOAT, NUMBER, STRING, SCALAR, ARRAY, HASH, CODE, UNDEF, DEFAULT and UNIVERSAL options can take
  240. three different types of value:
  241.  
  242. =over
  243.  
  244. =item *
  245.  
  246. A class name e.g.
  247.  
  248.     use autobox INTEGER => 'MyInt';
  249.  
  250. This binds the specified native type to the specified class. All methods invoked on
  251. literals or values of type C<key> will be dispatched as methods of the class specified in
  252. the corresponding C<value>.
  253.  
  254. =item *
  255.  
  256. A namespace: this is a class prefix (up to and including the final '::')
  257. to which the specified type name (INTEGER, FLOAT, STRING &c.) will be appended:
  258.  
  259. Thus:
  260.  
  261.     use autobox ARRAY => 'Prelude::';
  262.  
  263. is equivalent to:
  264.  
  265.     use autobox ARRAY => 'Prelude::ARRAY';
  266.  
  267. =item *
  268.  
  269. A reference to an array of class names and/or namespaces. This associates multiple classes with the
  270. specified type.
  271.  
  272. =back
  273.  
  274. =head2 DEFAULT
  275.  
  276. The C<DEFAULT> option specifies bindings for any of the four default types (SCALAR, ARRAY, HASH and CODE)
  277. not supplied in the C<use autobox> statement. As with the other options, the C<value> corresponding to
  278. the C<DEFAULT> C<key> can be a class name, a namespace, or a reference to an array containing one or
  279. more class names and/or namespaces.
  280.  
  281. Thus:
  282.  
  283.     use autobox
  284.         STRING  => 'MyString',
  285.         DEFAULT => 'MyDefault';
  286.  
  287. is equivalent to:
  288.  
  289.     use autobox
  290.         STRING  => 'MyString',
  291.         SCALAR  => 'MyDefault',
  292.         ARRAY   => 'MyDefault',
  293.         HASH    => 'MyDefault',
  294.         CODE    => 'MyDefault';
  295.  
  296. Which in turn is equivalent to:
  297.  
  298.     use autobox
  299.         INTEGER => 'MyDefault',
  300.         FLOAT   => 'MyDefault',
  301.         STRING  => [ 'MyString', 'MyDefault' ],
  302.         ARRAY   => 'MyDefault',
  303.         HASH    => 'MyDefault',
  304.         CODE    => 'MyDefault';
  305.  
  306. Namespaces in DEFAULT values have the default type name appended, which, in the case of defaulted SCALAR types,
  307. is SCALAR rather than INTEGER, FLOAT &c.
  308.  
  309. Thus:
  310.  
  311.     use autobox
  312.         ARRAY   => 'MyArray',
  313.         HASH    => 'MyHash',
  314.         CODE    => 'MyCode',
  315.         DEFAULT => 'MyNamespace::';
  316.  
  317. is equivalent to:
  318.  
  319.     use autobox
  320.         INTEGER => 'MyNamespace::SCALAR',
  321.         FLOAT   => 'MyNamespace::SCALAR',
  322.         STRING  => 'MyNamespace::SCALAR',
  323.         ARRAY   => 'MyArray',
  324.         HASH    => 'MyArray',
  325.         CODE    => 'MyCode';
  326.  
  327. Any of the four default types can be exempted from defaulting to the DEFAULT value by supplying a value of undef:
  328.  
  329.     use autobox
  330.         HASH    => undef,
  331.         DEFAULT => 'MyDefault';
  332.  
  333.     42->foo # ok: MyDefault::foo
  334.     []->bar # ok: MyDefault::bar
  335.  
  336.     %INC->baz # not ok: runtime error
  337.  
  338. =head2 UNDEF
  339.  
  340. The pseudotype, UNDEF, can be used to autobox undefined values. These are not autoboxed by default.
  341.  
  342. This doesn't work:
  343.  
  344.     use autobox;
  345.  
  346.     undef->foo() # runtime error
  347.  
  348. This works:
  349.  
  350.     use autobox UNDEF => 'MyUndef'; 
  351.  
  352.     undef->foo(); # ok
  353.  
  354. So does this:
  355.  
  356.     use autobox UNDEF => 'MyNamespace::'; 
  357.  
  358.     undef->foo(); # ok
  359.  
  360. =head2 NUMBER, SCALAR and UNIVERSAL
  361.  
  362. The virtual types NUMBER, SCALAR and UNIVERSAL function as macros or shortcuts which create
  363. bindings for their subtypes. The type hierarchy is as follows:
  364.  
  365.   UNIVERSAL -+
  366.              |
  367.              +- SCALAR -+
  368.              |          |
  369.              |          +- NUMBER -+
  370.              |          |          |
  371.              |          |          +- INTEGER
  372.              |          |          |
  373.              |          |          +- FLOAT
  374.              |          |
  375.              |          +- STRING
  376.              |
  377.              +- ARRAY
  378.              |
  379.              +- HASH
  380.              |
  381.              +- CODE
  382.   
  383. Thus:
  384.  
  385.     use autobox NUMBER => 'MyNumber';
  386.  
  387. is equivalent to:
  388.  
  389.     use autobox
  390.         INTEGER => 'MyNumber',
  391.         FLOAT   => 'MyNumber';
  392.  
  393. And:
  394.  
  395.     use autobox SCALAR => 'MyScalar';
  396.  
  397. is equivalent to:
  398.  
  399.     use autobox
  400.         INTEGER => 'MyScalar',
  401.         FLOAT   => 'MyScalar',
  402.         STRING  => 'MyScalar';
  403.  
  404. Virtual types can also be passed to C<unimport> via the C<no autobox> syntax. This disables autoboxing
  405. for the corresponding subtypes e.g.
  406.  
  407.     no autobox qw(NUMBER);
  408.  
  409. is equivalent to:
  410.  
  411.     no autobox qw(INTEGER FLOAT);
  412.  
  413. Virtual type bindings can be mixed with ordinary bindings to provide fine-grained control over
  414. inheritance and delegation. For instance:
  415.  
  416.     use autobox
  417.         INTEGER => 'MyInteger',
  418.         NUMBER  => 'MyNumber',
  419.         SCALAR  => 'MyScalar';
  420.  
  421. would result in the following bindings:
  422.  
  423.     42->foo             -> [ MyInteger, MyNumber, MyScalar ]
  424.     3.1415927->bar      -> [ MyNumber, MyScalar ]
  425.     "Hello, world!->baz -> [ MyScalar ]
  426.  
  427. Note that DEFAULT bindings take precedence over virtual type bindings i.e.
  428.  
  429.     use autobox
  430.         UNIVERSAL => 'MyUniversal',
  431.         DEFAULT   => 'MyDefault'; # default SCALAR, ARRAY, HASH and CODE before UNIVERSAL
  432.  
  433. is equivalent to:
  434.  
  435.   use autobox
  436.       INTEGER => [ 'MyDefault', 'MyUniversal' ],
  437.       FLOAT   => [ 'MyDefault', 'MyUniversal' ], # ... &c.
  438.  
  439. =head2 DEBUG
  440.  
  441. C<DEBUG> exposes the current bindings for the scope in which C<use autobox> is called by means
  442. of a callback, or a static debugging function.
  443.  
  444. This allows the computed bindings to be seen in "longhand".
  445.  
  446. The option is ignored if the value corresponding to the C<DEBUG> key is false.
  447.  
  448. If the value is a CODE ref, then this sub is called with a reference to
  449. the hash containing the computed bindings for the current scope.
  450.  
  451. Finally, if C<DEBUG> is true but not a CODE ref, the bindings are dumped
  452. to STDERR.
  453.  
  454. Thus:
  455.  
  456.     use autobox DEBUG => 1, ...
  457.  
  458. or
  459.  
  460.     use autobox DEBUG => sub { ... }, ...
  461.  
  462. or
  463.  
  464.     sub my_callback ($) {
  465.         my $hashref = shift;
  466.         ...
  467.     }
  468.  
  469.     use autobox DEBUG => \&my_callback, ...
  470.  
  471. =head1 METHODS
  472.  
  473. =head2 import
  474.  
  475. On its own, C<autobox> doesn't implement any methods that can be called on native types.
  476. However, its static method, C<import>, can be used to implement C<autobox> extensions i.e.
  477. lexically scoped modules that provide C<autobox> bindings for one or more native types without requiring
  478. calling code to C<use autobox>.
  479.  
  480. This is done by subclassing C<autobox> and overriding C<import>. This allows extensions to effectively
  481. translate C<use MyModule> into a bespoke C<use autobox> call. e.g.:
  482.  
  483.     package String::Trim;
  484.  
  485.     use base qw(autobox);
  486.  
  487.     sub import {
  488.         my $class = shift;
  489.         $class->SUPER::import(STRING => 'String::Trim::Scalar');
  490.     }
  491.  
  492.     package String::Trim::Scalar;
  493.  
  494.     sub trim {
  495.         my $string = shift;
  496.         $string =~ s/^\s+//;
  497.         $string =~ s/\s+$//;
  498.         $string;
  499.     }
  500.  
  501.     1;
  502.  
  503. Note that C<trim> is defined in an auxiliary class rather than in C<String::Trim> itself to prevent
  504. C<String::Trim>'s own methods (i.e. the methods it inherits from C<autobox>) being exposed to SCALAR types.
  505.  
  506. This module can now be used without a C<use autobox> statement to enable the C<trim> method in the current
  507. lexical scope. e.g.:
  508.  
  509.     #!/usr/bin/env perl
  510.  
  511.     use String::Trim;
  512.  
  513.     print "  Hello, world!  "->trim();
  514.  
  515. =head1 EXPORTS
  516.  
  517. =head2 autobox_class
  518.  
  519. C<autobox> makes a single method available to autoboxed types: C<autobox_class>. This can be used to
  520. call C<isa>, C<can>, C<VERSION>, C<import> and C<unimport>. e.g.
  521.  
  522.     if (42->autobox_class->isa('SCALAR')) ...
  523.     if (sub { ... }->autobox_class->can('curry')) ...
  524.  
  525. =head2 type
  526.  
  527. C<autobox> includes an additional module, C<autobox::universal>, which exports a single subroutine, C<type>.
  528.  
  529. This sub returns the type of its argument within C<autobox> (which is essentially longhand for the type names
  530. used within perl). This value is used by C<autobox> to associate a method invocant with its designated classes. e.g.
  531.  
  532.     use autobox::universal qw(type);
  533.  
  534.     type("Hello, world!") # STRING
  535.     type(42)              # INTEGER
  536.     type([])              # ARRAY
  537.     type(sub { })         # CODE
  538.  
  539. C<autobox::universal> is loaded automatically by C<autobox>, and, as its name suggests, can be used to install
  540. a universal method (i.e. a method for all C<autobox> types) e.g. 
  541.  
  542.     use autobox UNIVERSAL => 'autobox::universal';
  543.  
  544.     42->type        # INTEGER
  545.     3.1415927->type # FLOAT
  546.     %ENV->type      # HASH
  547.     
  548. =head1 CAVEATS
  549.  
  550. =head2 Performance
  551.  
  552. Autoboxing comes at a price. Calling
  553.  
  554.     "Hello, world!"->length()
  555.  
  556. is slightly slower than the equivalent method call on a string-like object, and significantly slower than
  557.  
  558.     length("Hello, world!")
  559.  
  560. =head2 Gotchas
  561.  
  562. =head3 Precedence
  563.  
  564. Due to Perl's precedence rules, some autoboxed literals may need to be parenthesized:
  565.  
  566. For instance, while this works:
  567.  
  568.     my $curried = sub { ... }->curry();
  569.  
  570. this doesn't:
  571.  
  572.     my $curried = \&foo->curry();
  573.  
  574. The solution is to wrap the reference in parentheses:
  575.  
  576.     my $curried = (\&foo)->curry();
  577.  
  578. The same applies for signed integer and float literals:
  579.  
  580.     # this works
  581.     my $range = 10->to(1);
  582.  
  583.     # this doesn't work
  584.     my $range = -10->to(10);
  585.  
  586.     # this works
  587.     my $range = (-10)->to(10);
  588.  
  589. =head3 print BLOCK
  590.  
  591. Perl's special-casing for the C<print BLOCK ...> syntax (see L<perlsub>) means that C<print { expression() } ...>
  592. (where the curly brackets denote an anonymous HASH ref) may require some further disambiguation:
  593.  
  594.     # this works (
  595.     print { foo => 'bar' }->foo();
  596.  
  597.     # and this
  598.     print { 'foo', 'bar' }->foo();
  599.  
  600.     # and even this
  601.     print { 'foo', 'bar', @_ }->foo();
  602.  
  603.     # but this doesn't
  604.     print { @_ }->foo() ? 1 : 0 
  605.  
  606. In the latter case, the solution is to supply something
  607. other than a HASH ref literal as the first argument
  608. to C<print()>:
  609.  
  610.     # e.g.
  611.     print STDOUT { @_ }->foo() ? 1 : 0;
  612.  
  613.     # or
  614.     my $hashref = { @_ };
  615.     print $hashref->foo() ? 1 : 0; 
  616.  
  617.     # or
  618.     print '', { @_ }->foo() ? 1 : 0; 
  619.  
  620.     # or
  621.     print '' . { @_ }->foo() ? 1 : 0; 
  622.  
  623.     # or even
  624.     { @_ }->print_if_foo(1, 0); 
  625.  
  626. =head3 eval EXPR
  627.  
  628. Like most pragmas autobox performs some of its operations at compile time, and,
  629. as a result, runtime string C<eval>s are not executed within its scope i.e. this
  630. doesn't work:
  631.  
  632.     use autobox;
  633.  
  634.     eval "42->foo";
  635.  
  636. The workaround is to use autobox within the C<eval> e.g.
  637.  
  638.     eval <<'EOS';
  639.         use autobox;
  640.         42->foo(); 
  641.     EOS
  642.  
  643. Note that the C<eval BLOCK> form works as expected:
  644.  
  645.     use autobox;
  646.     
  647.     eval { 42->foo() }; # OK
  648.         
  649. =head1 VERSION
  650.  
  651. 2.70
  652.  
  653. =head1 SEE ALSO
  654.  
  655. =over
  656.  
  657. =item * L<autobox::Core|autobox::Core>
  658.  
  659. =item * L<Moose::Autobox>
  660.  
  661. =item * L<perl5i|perl5i>
  662.  
  663. =item * L<Scalar::Properties|Scalar::Properties>
  664.  
  665. =back
  666.  
  667. =head1 AUTHOR
  668.     
  669. chocolateboy <chocolate@cpan.org>
  670.  
  671. =head1 COPYRIGHT
  672.  
  673. Copyright (c) 2003-2010, chocolateboy.
  674.  
  675. This module is free software. It may be used, redistributed
  676. and/or modified under the same terms as Perl itself.
  677.  
  678. =cut
  679.